<template>
  <div id="vxePulldownSelection">
    <vxe-pulldown :ref="'xDown4' + compId" transfer span="24" style="width: 100%">
      <template #default>
        <!-- @focus="focusEvent4" -->
        <vxe-input :ref="`inputRef${compId}`" class="enterNextInputFlag" v-model="keyvalue" autocomplete="off" :disabled="caUse" :readonly="isReadonly" suffix-icon="vxe-icon-search" placeholder="请选择" @keydown="enterConfirmEvent" @dblclick="focusEvent4" @blur="blurEvent4" @change="inputChange" @suffix-click="suffixClick4" @clear="clearConfirmEvent" clearable></vxe-input>
      </template>
      <template #dropdown>
        <div class="my-dropdown4 radius round shadow-warp lines-orange solid">
          <vxe-toolbar class-name="title-bar">
            <template #buttons>
              <span class="text-bold">{{selCurGridRowTxt?`已选; ${selCurGridRowTxt}`:`请选择`}}</span>
            </template>
            <template #tools>
              <span class="flex justify-end text-bold text-black" style="font-size: 1.15rem; cursor: pointer" @click="closePanel">
                <i class="vxe-icon-error-circle-fill"></i>
              </span>
            </template>
          </vxe-toolbar>
          <Splitpanes class="content-box">
            <Pane size="30">
              <div class="left-panel" :style="{ height: '100%' }">
                <vxe-table ref="dictCategoriesRef" :data="dictCategories" height="auto" :row-config="{ isCurrent: true }" @cell-click="categoryTableCellClick">
                  <vxe-column type="seq" width="30" title="#"></vxe-column>
                  <vxe-column field="name" title="类别"></vxe-column>
                </vxe-table>
              </div>
            </Pane>
            <Pane size="70">
              <vxe-toolbar perfect v-if="isShowQuickCondition">
                <template #buttons>
                  <div style="height: 24px">
                    <vxe-radio-group v-model="quickConditionsValue" @change="radioChange">
                      <vxe-radio :label="null" content="全部"></vxe-radio>
                      <vxe-radio :label="1" content="常见"></vxe-radio>
                      <vxe-radio :label="0" content="不常见"></vxe-radio>
                    </vxe-radio-group>
                  </div>
                </template>
              </vxe-toolbar>
              <div :style="{ height: 'calc(100%)' }">
                <vxe-grid :ref="'gridTable4' + compId" :scroll-y="{enabled: true}" :auto-resize="true" border show-overflow height="auto" width="auto" :row-config="{ isHover: true, isCurrent: true }" :keyboard-config="{
                    isArrow: true,
                    isEnter: true,
                    editMethodExmItem4
                  }" :edit-config="{ mode: 'row' }" :column-config="{ resizable: false }" :loading="loading" :pager-config="isPage ? tablePage4 : null" :data="tableList" :columns="tableColumn" @cell-click="bacCellCLick" @cell-dblclick="cellClickEvent4" @page-change="pageChangeEvent4" @keydown="gridKeyDown"></vxe-grid>
              </div>
            </Pane>
          </Splitpanes>
        </div>
      </template>
    </vxe-pulldown>
    <!-- <span>这是组件</span> -->
  </div>
</template>
<script lang="ts" setup>
//#region  依赖注入
import { ref, reactive, getCurrentInstance, nextTick, onMounted, watch, computed } from 'vue';
import { pageSizes, IsEmpty, newGuid } from '@/utils/common';
import { Splitpanes, Pane } from 'splitpanes';

//#region  变量
const dictCategoriesRef: any = ref(null);
let { proxy }: any = getCurrentInstance();
let a = reactive(pageSizes);
let b = ref(newGuid());
let compId: string = newGuid();
let keyvalue = ref('');
let caUse = ref(false);
let isReadonly = ref(false);
let loading = ref(false);
let tablePage4 = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 200
});
let tableList = reactive([]);
//let tableColumn = reactive([]);
let totalCount = 0;
let dictCategories: any[] = reactive([]); /**字典分类 */
let selectedItem = {
  id: null,
  name: ''
};
let curSelectCategoryObj: any = reactive({});
let quickConditionsValue = ref(null);
let selCurGridRow: any = reactive({});
let selCurGridRowTxt = ref('');
// 父组件传值
let props = defineProps({
  url: String, //数据请求地址
  requestType: { type: String, default: 'get' }, //请求方式
  tableColumn: Array as () => String[], //列集合
  displayTexts: Array as () => String[], //显示字段集合
  displayTextObj: String, //显示字段集合
  dataObj: {}, //接口参数。{key1:value1,key2:value2...}
  isDisabled: Boolean, //是否可用
  isReadonly: Boolean, //是否只读
  isChild: Boolean, //是否子行
  childIndex: Number, //子航索引
  aimKeys: Array as () => String[], //目标字段
  isChangeName: Boolean, //输入框内容是否可手动更改
  compName: String, //组件名称
  isRow: Boolean,
  rowIndex: String,
  panelWidth: { type: String, default: '450px' },
  panelHeight: { type: String, default: '300px' },
  isPage: { type: Boolean, default: false }, //是否需要分页
  isShowQuickCondition: { type: Boolean, default: true } /**是否显示快速筛选条件 */,
  dictTypeCode: { type: String, default: '' } /**字典编码 */
}) as any;

// watch(
//   () => props.displayTextObj,
//   (n, o) => {
//     keyvalue.value = n;
//     if (!tableList || tableList.length <= 0) {
//       findList();
//     }
//   },
//   {
//     deep: true,
//     immediate: true
//   }
// );

watch(
  () => props.isDisabled,
  (newval, oldvbal) => {
    caUse.value = newval;
  },
  {
    deep: true,
    immediate: true
  }
);

watch(
  () => props.displayTextObj,
  (newval, oldvbal) => {
    keyvalue.value = newval;
  },
  {
    deep: true,
    immediate: true
  }
);
//#endregion

//#region  计算属性
const inputText = computed(() => {
  // let v = '';
  // try {
  //   const aim = tableList.filter((p) => p[props.aimKeys[0].rowKey] === keyvalue.value);
  //   if (aim && aim.length > 0) {
  //     v = aim[0][props.tableColumn[1].field];
  //   }
  //   return v;
  // } catch (error) {
  //   v = '';
  // }
  return keyvalue.value;
});
//#endregion

//#region  属性

//#endregion

//#region  监听器

//#endregion

//#endregion

defineExpose({
  resetDisplayText /**重置显示文本 */
});

//#region  生命周期函数
onMounted(() => {
  findDictCategories();
});
//#endregion

//#region  函数
/**查询字典分类数据 */
function findDictCategories() {
  proxy.$http
    .get('/api/sys/basDictDetail/findDictDetailList', { params: { code: props.dictTypeCode ? props.dictTypeCode : '!@Q#WE$' } })
    .then(async (res: any) => {
      dictCategories.length = 0;
      if (res && res.data && res.data.length >= 0) {
        Object.assign(dictCategories, res.data);
        //Object.assign(curSelectCategoryObj, res.data[0]);
        //findList();
        if (dictCategoriesRef.value) {
          dictCategoriesRef.value?.setCurrentRow(res.data[0]);
        }
      }
    })
    .catch((err: any) => {
      //ToDo
    });
}

function findList() {
  loading.value = true;
  tableList.length = 0;
  if (IsEmpty(proxy.url)) {
    loading.value = false;
    return;
  }

  let url = proxy.url;
  let data: any = {
    filter: IsEmpty(selectedItem.name) ? null : selectedItem.name.toString().trim().toUpperCase(),
    sorting: null,
    skipCount: (tablePage4.currentPage - 1) * tablePage4.pageSize,
    maxResultCount: tablePage4.pageSize,
    pageIndex: 1,
    pageSize: 20000
    //inputCode:IsEmpty(this.selectedItem.name) ? null : this.selectedItem.name.toString().trim().toUpperCase(),
  };

  // if (IsEmpty(curSelectCategoryObj.code)) {
  //   loading.value = false;
  //   return;
  // }

  if (!IsEmpty(keyvalue.value)) {
    data['searchValue'] = keyvalue.value;
    curSelectCategoryObj.code = '';
  }

  if (!IsEmpty(curSelectCategoryObj.code)) {
    data.germType = curSelectCategoryObj.code;
  }

  if (!IsEmpty(curSelectCategoryObj.code)) {
    data.antType = curSelectCategoryObj.code;
  }

  if (!IsEmpty(quickConditionsValue.value)) {
    data['isCommon'] = quickConditionsValue.value;
  }


  // 循环父组件传来的特殊查询字段，添加到data上
  if (!IsEmpty(proxy.dataObj)) {
    for (const key in proxy.dataObj) {
      if (proxy.dataObj[key]) {
        data[key] = proxy.dataObj[key];
      }
    }
  }

  /**位置顺序蹦年改变 */
  if (!IsEmpty(props.displayTextObj)) {
    keyvalue.value = props.displayTextObj;
    // try {
    //   const $bacTestResultRef = proxy.$refs['inputRef' + compId] as any;
    //   $bacTestResultRef.select();
    // } catch (error) { }
  }

  if (proxy.requestType === 'post') {
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        tableList.push(...res.data);
        loading.value = false;
        proxy.$nextTick(() => {
          const $xTable = proxy.$refs['gridTable4' + compId] as any;
          if ($xTable) {
            $xTable.focus();
            if (tableList.length > 0) {
              $xTable.setCurrentRow(tableList[0]);
              selCurGridRowTxt.value = tableList[0][props.displayTexts[0]];
            }
          }
        });
      })
      .catch((err: any) => {
        loading.value = false;
      });
  } else {
    proxy.$http
      .get(url, { params: data })
      .then((res: any) => {
        tableList.push(...res.data);
        loading.value = false;
        proxy.$nextTick(() => {
          const $xTable = proxy.$refs['gridTable4' + compId] as any;
          if ($xTable) {
            $xTable.focus();
            if (tableList.length > 0) {
              $xTable.setCurrentRow(tableList[0]);
              selCurGridRowTxt.value = tableList[0][props.displayTexts[0]];
            }
          }
        });
      })
      .catch((err: any) => {
        loading.value = false;
      });
  }
}

/**重置显示信息 */
function resetDisplayText(text: String, callback) {
  if (tableList.length <= 0) {
    findList();
  }
  keyvalue.value = text;
  if (callback) {
    callback();
  }
}

// 获取列表
function findListWithUrl(pUrl: string) {
  if (IsEmpty(pUrl)) {
    tableList = [];
    return;
  }
  //#region  判断请求接口地址为空
  if (IsEmpty(proxy.url)) {
    loading.value = false;
    tableList = [];
    return;
  }
  //#endregion
  let url = pUrl;
  let data: any = {
    filter: IsEmpty(selectedItem.name) ? null : selectedItem.name.toString().trim(),
    sorting: null,
    skipCount: (tablePage4.currentPage - 1) * tablePage4.pageSize,
    maxResultCount: tablePage4.pageSize
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      tableList = res.data; //.push(...res.data);
      tablePage4.total = res.totalCount;
      // this.$forceUpdate();
      loading.value = false;
    })
    .catch((err: any) => {
      //loading = false;
      //.$alert(err.data.error.message, '提示');
    });
}

//回车选中
function enterConfirmEvent({ value, $event }) {
  if ($event && ($event.keyCode === 13 || $event.keyCode === 9)) {
    const $xTable = proxy.$refs['xDown4' + compId] as any;
    if ($xTable.isPanelVisible()) {
      //todo
    } else {
      findList();
      $xTable.showPanel();
    }
  }
}

/**关闭弹窗 */
function closePanel() {
  const $xTable = proxy.$refs['xDown4' + compId] as any;
  if ($xTable) {
    $xTable.hidePanel();
  }
}

// 获取焦点
function focusEvent4() {
  try {
    const $bacTestResultRef = proxy.$refs['inputRef' + compId] as any;
    $bacTestResultRef.select();
  } catch (error) { }
  const $xTable = proxy.$refs['xDown4' + compId] as any;
  if (!IsEmpty(curSelectCategoryObj.code)) {
    categoryTableCellClick({ row: curSelectCategoryObj });
  }
  if ($xTable.isPanelVisible()) {
    return;
  }
  if ($xTable) {
    $xTable.showPanel();
    findList();
  }
}
// 失去焦点
function blurEvent4(e) {
  // 输入框内容未改变
  if (e.value === proxy.displayTextObj) {
    return;
  }
  if (proxy.isChangeName) {
    this.$emit('changeName', e.value);
  }
}

// 值改变
function inputChange({ value }) {
  findList();
}

function keyupEvent4() {
  const $xTable = proxy.$refs['xDown4' + compId] as any;
  $xTable.showPanel();
}

function suffixClick4() {
  const $xTable = proxy.$refs['xDown4' + compId] as any;
  $xTable.togglePanel();
}
// 清空
function clearConfirmEvent() {
  //todo
  proxy.$emit('confirmClick', {
    isChild: proxy.isChild,
    childIndex: proxy.childIndex,
    row: { ...{ id: null }, entity: { id: null } },
    aimKeys: proxy.aimKeys,
    compName: proxy.compName
  });
}
function editMethodExmItem4() {
  //todo
}
/**当行选中 */
function bacCellCLick({ row }) {
  selCurGridRowTxt.value = row[props.displayTexts[0]];
  const $tabGrid = proxy.$refs['gridTable4' + compId] as any;
  $tabGrid.focus();
}
//行选中
function cellClickEvent4({ row, $event }) {
  if (IsEmpty(row)) {
    return;
  }
  keyvalue.value = '';
  proxy.displayTexts.forEach((element) => {
    // 判断父组件传来的数据是否是对象的深层键名
    const keyArr = element.split('.');
    if (keyArr.length > 1) {
      let res = null;
      let data = row;
      keyArr.forEach((key, index) => {
        if (index > 0) {
          data = res;
        }
        res = data[key];

        if (index === keyArr.length - 1) {
          keyvalue.value += res + ' ';
        }
      });
    } else {
      keyvalue.value += row[element] + ' ';
    }
  });

  proxy.$emit('confirmClick', {
    isRow: proxy.isRow,
    rowIndex: proxy.rowIndex,
    row: { ...row, entity: row },
    aimKeys: proxy.aimKeys,
    compName: proxy.compName,
    isChild: proxy.isChild,
    childIndex: proxy.childIndex
  });
  const $xTable = proxy.$refs['xDown4' + compId] as any;
  $xTable.hidePanel();
}
/**表格按键按下 */
function gridKeyDown({ $event }) {
  if ($event.keyCode === 13) {
    const $xTable = proxy.$refs['xDown4' + compId] as any;
    if ($xTable.isPanelVisible()) {
      const gridTable = proxy.$refs['gridTable4' + compId] as any;
      const rowSelect = gridTable.getCurrentRecord();
      cellClickEvent4({ row: rowSelect });
      $xTable.hidePanel();
    } else {
      findList();
      $xTable.showPanel();
    }
  }
}
/**页号改变 */
function pageChangeEvent4({ type, currentPage, pageSize }) {
  tablePage4.currentPage = currentPage;
  tablePage4.pageSize = pageSize;
  findList();
}
function selectRow() {
  (proxy.$refs.table as any).setCurrentRow(proxy.tableList[0]);
}
/**快速筛选条件该百年 */
function radioChange(e) {
  findList();
}
/**类别单元格点击事件 */
function categoryTableCellClick({ row }) {
  Object.assign(curSelectCategoryObj, row);
  findList();
}
//#endregion
</script>
<style lang="scss" scoped>
.my-dropdown4 {
  width: 700px;
  border: 1px solid #c5c5c5;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  flex-wrap: wrap;

  .content-box {
    height: 460px;
    min-height: 460px;
  }
}

.title-bar {
  height: 40px;
  background-color: #f0f0f0;
  border-bottom: 1px solid #c5c5c5;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  display: flex;
  align-items: center;
  padding: 0 12px;
  font-weight: 700;
}

.vxe-pulldown {
  width: 100%;
}

.vxe-table-no-select {
  user-select: none;
}

:deep(.vxe-pager--goto) {
  height: 24px !important;
}

.splitpanes__pane {
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1) inset;
}

.splitpanes--vertical > .splitpanes__splitter {
  min-width: 6px;
  background: linear-gradient(90deg, rgb(226, 226, 226), rgb(226, 226, 226));
}

.splitpanes--horizontal > .splitpanes__splitter {
  min-height: 6px;
  background: linear-gradient(0deg, rgb(226, 226, 226), rgb(226, 226, 226));
}
</style>
